package org.dentalcard.ui.tools;

import javax.swing.*;
import javax.swing.text.DateFormatter;
import javax.swing.text.DefaultFormatterFactory;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @user: Vladimir Chernishov
 * @date: 21.12.11
 * @time: 12:04
 */
public class DateTextField extends JFormattedTextField {

    private final String pattern;

    public DateTextField() {
        this("MM/dd/yyyy");
    }

    public DateTextField(final String pattern) {

        this.pattern = pattern;

        DateFormatter formatter = new DateInputFormatter(this.pattern);

        setFormatterFactory(new DefaultFormatterFactory(formatter));
        setHorizontalAlignment(JTextField.CENTER);

        setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT);

    }

    public void setValueToNull() {
        super.setText(this.pattern.toUpperCase());
        super.setValue(null);
    }

    public Date getDate() {
        return (Date) super.getValue();
    }

    static class DateInputFormatter extends DateFormatter {

        /**
         *
         */
        private static final long serialVersionUID = -443141138249611327L;

        private String pattern = null;

        public DateInputFormatter(String pattern) {
            super(new SimpleDateFormat(pattern));
            this.pattern = pattern.toUpperCase();
        }

        public Object stringToValue(String text) throws ParseException {
            if (text == null || text.trim().length() == 0 || text.trim().equals(this.pattern))
                return null;
            return super.stringToValue(text);
        }

        public String valueToString(Object value) throws ParseException {
            if (value == null)
                return this.pattern;
            return super.valueToString(value);
        }
    }
}
